package Lee_code;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author blh
 * @date 2024年08月07日 17:04
 */
public class Lee_692_87 {
    public List<String> topKFrequent(String[] words, int k) {
        int len = words.length;
        HashMap<String, Integer> seen = new HashMap<>();
        for (String word : words) {
            seen.put(word, seen.getOrDefault(word, 0) + 1);
        }
        // 先字典后频率
        List<String> list = new ArrayList<>(seen.keySet());

        // 字典排序
        list.sort((o1, o2) -> {
            char[] char1 = o1.toCharArray();
            char[] char2 = o2.toCharArray();
            int len1 = char1.length;
            int len2 = char2.length;
            int commonLen = Math.min(len1, len2);
            for (int i = 0; i < commonLen; i++) {
                if (char1[i] < char2[i]) {
                    return -1;
                } else if (char1[i] > char2[i]) {
                    return 1;
                }
            }
            return Integer.compare(len1, len2);
        });

        // 这是频率
        list.sort((o1, o2) -> {
            int freq1 = seen.get(o1);
            int freq2 = seen.get(o2);
            return -Integer.compare(freq1, freq2);
        });

        while (list.size() > k) {
            list.remove(list.size() - 1);
        }
        return list;
    }
}
